package com.aiyige.page.follow.adapter;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.sns.Follow;
import com.aiyige.model.sns.backup.SnsMineBackup;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.WebImageUrlModifier;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by zhuyakun on 2018/1/31.
 */

public class FollowAdapter extends BaseQuickAdapter<Follow, FollowAdapter.ViewHolder> {

    public FollowAdapter() {
        super(R.layout.sns_relationship_item, new LinkedList<Follow>());
    }

    @Override
    protected void convert(ViewHolder helper, Follow item) {
        helper.bindData(item);
    }

    public class ViewHolder extends BaseViewHolder {
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.userNameTv)
        TextView userNameTv;
        @BindView(R.id.followLayout)
        LinearLayout followLayout;
        @BindView(R.id.followedLayout)
        LinearLayout followedLayout;
        @BindView(R.id.mutualfollowedLayout)
        LinearLayout mutualfollowedLayout;
        Follow data;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        @OnClick({R.id.followLayout, R.id.followedLayout, R.id.mutualfollowedLayout, R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.followLayout:
                    if (AccountUtil.isLogin()) {
                        new AddFollowTask().execute();
                    } else {
                        ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
                    }
                    break;
                case R.id.followedLayout:
                case R.id.mutualfollowedLayout:
                    if (AccountUtil.isLogin()) {
                        new DeleteFollowTask().execute();
                    } else {
                        ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
                    }
                    break;

                case R.id.containerLayout:
                    ARouter.getInstance()
                            .build(ARouterConfig.UserPage)
                            .withString("userId", data.getBeFollowedId())
                            .navigation();
                    break;
            }
        }

        public void bindData(Follow follow) {
            data = follow;
            GlideUtil.with(itemView.getContext()).small().loadAvatar(WebImageUrlModifier.mediumImage(data.getFollowUserBackup().getAvatar()))
                    .into(avatarIv);
            userNameTv.setText(data.getFollowUserBackup().getName());
            if (data.getMineBackup().getIsMe() == SnsMineBackup.IS_ME_YES) {
                followLayout.setVisibility(View.INVISIBLE);
                followedLayout.setVisibility(View.INVISIBLE);
                mutualfollowedLayout.setVisibility(View.INVISIBLE);
            } else {
                if (TextUtils.isEmpty(data.getMineBackup().getMyFollowId())) {
                    followLayout.setVisibility(View.VISIBLE);
                    followedLayout.setVisibility(View.INVISIBLE);
                    mutualfollowedLayout.setVisibility(View.INVISIBLE);
                } else if (data.getMutualFollower()) {
                    followLayout.setVisibility(View.INVISIBLE);
                    followedLayout.setVisibility(View.INVISIBLE);
                    mutualfollowedLayout.setVisibility(View.VISIBLE);
                } else {
                    followLayout.setVisibility(View.INVISIBLE);
                    followedLayout.setVisibility(View.VISIBLE);
                    mutualfollowedLayout.setVisibility(View.INVISIBLE);
                }
            }
        }


        public class AddFollowTask extends AsyncTask<Object, Object, Object> {
            LoadingDialog loadingDialog;

            @Override
            protected void onPreExecute() {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(itemView.getContext())
                        .show();
            }

            @Override
            protected Object doInBackground(Object... objects) {
                try {
                    Response<ResponseBody> response = ApiManager.getService().addFollow(Follow.newBuilder()
                            .beFollowedId(data.getBeFollowedId())
                            .followerId(AccountUtil.getCurrentUser().getId())
                            .build())
                            .execute();
                    if (response.code() != ResponseCode.CREATED) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Follow follow = JSON.parseObject(json, Follow.class);
                    if (follow == null) {
                        throw new Exception("添加关注失败");
                    }
                    return new Follow(follow);
                } catch (Exception e) {
                    return e;
                }
            }

            @Override
            protected void onPostExecute(Object o) {
                loadingDialog.dismiss();
                if (o instanceof Exception) {
                    ToastX.show(((Exception) o).getMessage());
                } else {
                    data.getMineBackup().setMyFollowId(((Follow) o).getId());
                    data.setMutualFollower(((Follow) o).getMutualFollower());
                    bindData(data);
                }
            }
        }

        public class DeleteFollowTask extends AsyncTask<Object, Object, Object> {
            LoadingDialog loadingDialog;

            @Override
            protected void onPreExecute() {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(itemView.getContext())
                        .show();
            }

            @Override
            protected Object doInBackground(Object... objects) {
                try {
                    Response<ResponseBody> response = ApiManager.getService()
                            .deleteFollow(data.getMineBackup().getMyFollowId())
                            .execute();
                    if (response.code() != ResponseCode.NO_CONTENT) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    return null;
                } catch (Exception e) {
                    return e;
                }
            }

            @Override
            protected void onPostExecute(Object o) {
                loadingDialog.dismiss();
                if (o instanceof Exception) {
                    ToastX.show(((Exception) o).getMessage());
                } else {
                    try {
                        remove(getAdapterPosition() - getHeaderLayoutCount());
                    } catch (Exception e) {

                    }
//                    data.getMineBackup().setMyFollowId("");
//                    bindData(data);
                }
            }
        }
    }
}
